import puppeteer from 'puppeteer';
import { createLogger } from '../modules/Logger.js';

const waitTimeInSeconds = 3;
const logPrefix = '皮皮の截图';

export class WebPreview extends plugin {
  constructor() {
    super({
      name: '截图预览网页内容',
      dsc: '检测到网页地址时截图预览网页内容',
      event: 'message',
      priority: -10,
      rule: [
        {
          reg: '^(http|https)://.*',
          fnc: 'WebPreview',
        },
      ],
    });
    
    // 初始化日志实例（自动绑定插件名称）
    this.logger = createLogger(this.name);
  }

  async WebPreview(e) {
    let url = e.msg;
    if (!/^(http|https):\/\//i.test(url)) {
      url = `https://${url}`;
      this.logger.info(`${logPrefix} 转换链接: ${url}`); 
    }

    const browser = await puppeteer.launch({
      headless: true,
      args: [
        '--disable-gpu',
        '--disable-dev-shm-usage',
        '--disable-setuid-sandbox',
        '--no-first-run',
        '--no-sandbox',
        '--no-zygote', 
        '--single-process',
      ],
    });

    let page;
    try {
      page = await browser.newPage();
      await page.goto(url);
      this.logger.info(`${logPrefix} 打开链接: ${url}`);  
      await e.reply('检测到链接，正在准备截图，请稍等片刻...', true);

      this.logger.info(`${logPrefix} 等待 ${waitTimeInSeconds} 秒...`);  
      await new Promise((resolve) => setTimeout(resolve, waitTimeInSeconds * 1000));

      this.logger.info(`${logPrefix} 开始截图网页内容`); 
      await page.setViewport({
        width: 1920,
        height: 1080,
      });

      const screenshotBase64 = await page.screenshot({ 
        fullPage: true,
        encoding: 'base64',
        type: 'png'
      });

      await e.reply(segment.image(`base64://${screenshotBase64}`), true);
    } catch (error) {
      this.logger.error(`${logPrefix} 截图失败`, error);  
      await e.reply('截图失败，请稍后再试或检查链接是否有效！', true);
    } finally {
      if (page) {
        await page.close();
      }
      await browser.close();
      this.logger.info(`${logPrefix} 浏览器关闭: ${url}`); 
    }
  }
}

export default new WebPreview();